<template>
  <div class="chat-wrapper">
    <!-- 顶部 -->
    <header class="chat-header">
      <div class="logo">
        <span class="icon">🤖</span>
        <h1>GPT 聊天助手</h1>
      </div>
      <div class="status" :class="{ online: isOnline }">
        <span class="dot"></span>
        {{ isOnline ? '在线' : '离线' }}
      </div>
    </header>

    <!-- 消息区域 -->
    <main class="chat-body" ref="messagesContainer">
      <transition-group name="fade" tag="div">
        <div v-for="message in messages" :key="message.id" :class="['message', message.role]">
          <div class="avatar" v-if="message.role === 'assistant'">🤖</div>
          <div class="bubble">
            <p class="text">{{ message.content }}</p>
            <span class="time">{{ message.time }}</span>
          </div>
          <div class="avatar user" v-if="message.role === 'user'">你</div>
        </div>
      </transition-group>

      <div v-if="loading" class="message assistant">
        <div class="avatar">🤖</div>
        <div class="bubble typing">
          <span></span><span></span><span></span>
        </div>
      </div>
    </main>

    <!-- 输入区域 -->
    <footer class="chat-input">
      <div class="input-area">
        <textarea
          v-model="inputMessage"
          @keydown="handleKeydown"
          placeholder="和我聊点什么吧..."
          rows="1"
          ref="textareaRef"
        ></textarea>
        <button @click="sendMessage" :disabled="loading || !inputMessage.trim()" class="send-btn">
          <svg v-if="!loading" xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor">
            <path d="M2 21l21-9L2 3v7l15 2-15 2v7z"/>
          </svg>
          <div v-else class="spinner"></div>
        </button>
      </div>
      <small class="hint">Enter 发送 · Shift + Enter 换行</small>
    </footer>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from 'vue'
import axios from 'axios'

const API_BASE_URL = 'http://localhost:5000/api'

const inputMessage = ref('')
const loading = ref(false)
const messages = ref([])
const isOnline = ref(true)
const messagesContainer = ref(null)
const textareaRef = ref(null)

const sendMessage = async () => {
  if (!inputMessage.value.trim() || loading.value) return
  const userMessage = {
    id: Date.now(),
    role: 'user',
    content: inputMessage.value,
    time: new Date().toLocaleTimeString()
  }
  messages.value.push(userMessage)
  const currentMessage = inputMessage.value
  inputMessage.value = ''
  loading.value = true
  adjustTextareaHeight()

  try {
    const response = await axios.post(`${API_BASE_URL}/chat`, { message: currentMessage })
    const aiMessage = {
      id: Date.now() + 1,
      role: 'assistant',
      content: response.data?.data?.response || '抱歉，我现在无法响应。',
      time: new Date().toLocaleTimeString()
    }
    messages.value.push(aiMessage)
  } catch (err) {
    messages.value.push({
      id: Date.now() + 1,
      role: 'assistant',
      content: `出现错误：${err.message}`,
      time: new Date().toLocaleTimeString()
    })
  } finally {
    loading.value = false
    scrollToBottom()
  }
}

const handleKeydown = (e) => {
  if (e.key === 'Enter' && !e.shiftKey) {
    e.preventDefault()
    sendMessage()
  }
}

const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value)
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  })
}

const adjustTextareaHeight = () => {
  nextTick(() => {
    if (textareaRef.value) {
      textareaRef.value.style.height = 'auto'
      textareaRef.value.style.height = Math.min(textareaRef.value.scrollHeight, 150) + 'px'
    }
  })
}

watch(inputMessage, adjustTextareaHeight)

onMounted(() => {
  const welcome = {
    id: 1,
    role: 'assistant',
    content: '你好，我是 GPT 聊天助手，有什么我可以帮你的吗？ 😊',
    time: new Date().toLocaleTimeString()
  }
  messages.value.push(welcome)
  scrollToBottom()
})
</script>

<style scoped>
/* ===== 全局样式 ===== */
.chat-wrapper {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: var(--bg);
  color: var(--text);
  font-family: 'Inter', 'PingFang SC', sans-serif;
  transition: background 0.3s, color 0.3s;
}

:root {
  --bg: #f7f9fc;
  --text: #333;
  --bubble-user: #1976d2;
  --bubble-ai: #fff;
  --border: #e2e8f0;
}

@media (prefers-color-scheme: dark) {
  :root {
    --bg: #1e1e2f;
    --text: #e2e2e2;
    --bubble-user: #2563eb;
    --bubble-ai: #2b2b3c;
    --border: #3a3a4a;
  }
}

/* ===== 顶部 ===== */
.chat-header {
  padding: 12px 20px;
  border-bottom: 1px solid var(--border);
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: rgba(255,255,255,0.6);
  backdrop-filter: blur(10px);
}

.logo {
  display: flex;
  align-items: center;
  gap: 8px;
}

.logo .icon {
  font-size: 20px;
}

.status {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  color: #666;
}

.status .dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #999;
}

.status.online .dot {
  background: #4caf50;
}

/* ===== 消息区 ===== */
.chat-body {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.message {
  display: flex;
  align-items: flex-end;
  gap: 10px;
  max-width: 80%;
  animation: fadeIn 0.3s ease;
}

.message.user {
  margin-left: auto;
  flex-direction: row-reverse;
}

.bubble {
  background: var(--bubble-ai);
  padding: 12px 16px;
  border-radius: 14px;
  box-shadow: 0 2px 6px rgba(0,0,0,0.08);
  line-height: 1.6;
}

.user .bubble {
  background: var(--bubble-user);
  color: white;
}

.bubble.typing {
  display: flex;
  gap: 4px;
}

.typing span {
  width: 6px;
  height: 6px;
  background: #999;
  border-radius: 50%;
  animation: typing 1.4s infinite ease-in-out;
}

.typing span:nth-child(1) { animation-delay: -0.32s; }
.typing span:nth-child(2) { animation-delay: -0.16s; }

@keyframes typing {
  0%, 80%, 100% { transform: scale(0); }
  40% { transform: scale(1); }
}

.avatar {
  font-size: 14px;
  color: white;
  width: 32px;
  height: 32px;
  background: #2563eb;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.user .avatar {
  background: #666;
}

.time {
  display: block;
  font-size: 11px;
  color: #aaa;
  margin-top: 4px;
}

/* ===== 输入区 ===== */
.chat-input {
  position: fixed;
  bottom: 24px;              /* 👈 距离底部留出空间 */
  left: 50%;
  transform: translateX(-75%);
  width: 90%;
  max-width: 800px;
  border-radius: 16px;       /* 圆角外观 */
  border: 1px solid var(--border);
  background: rgba(255, 255, 255, 0.9);  /* 半透明背景 */
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);  /* 阴影效果 */
  padding: 16px 20px;
  backdrop-filter: blur(12px);  /* 毛玻璃感 */
  z-index: 100;
}


.input-area {
  display: flex;
  align-items: flex-end;
  gap: 12px;
}

textarea {
  flex: 1;
  resize: none;
  border: 1px solid var(--border);
  border-radius: 10px;
  padding: 12px 14px;
  font-size: 14px;
  line-height: 1.6;
  background: var(--bubble-ai);
  color: var(--text);
  outline: none;
}

.send-btn {
  width: 44px;
  height: 44px;
  border: none;
  border-radius: 10px;
  background: #2563eb;
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.send-btn:hover:not(:disabled) {
  background: #1e4ed8;
}

.send-btn:disabled {
  background: #999;
  cursor: not-allowed;
}

.spinner {
  width: 16px;
  height: 16px;
  border: 2px solid transparent;
  border-top: 2px solid white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.hint {
  display: block;
  text-align: center;
  font-size: 12px;
  color: #888;
  margin-top: 6px;
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(5px); }
  to { opacity: 1; transform: translateY(0); }
}
</style>
